import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Dict } from 'src/database/entitys/dict.entity';
import { DictData } from 'src/database/entitys/dict-data.entity';
import { CreateDictDto } from './dto/create-dict.dto';
import { UpdateDictDto } from './dto/update-dict.dto';
import { PageDto } from 'src/common/dto/page.dto';

/**
 * 字典服务类
 * 处理字典相关的业务逻辑
 */
@Injectable()
export class DictService {
  constructor(
    @InjectRepository(Dict)
    private dictRepository: Repository<Dict>,
    @InjectRepository(DictData)
    private dictDataRepository: Repository<DictData>
  ) {}

  /**
   * 创建字典
   * @param createDictDto 创建字典的数据传输对象
   * @returns 创建的字典实体
   */
  async create(createDictDto: CreateDictDto): Promise<Dict> {
    const dict = this.dictRepository.create(createDictDto);
    return await this.dictRepository.save(dict);
  }

  /**
   * 分页查询字典列表
   * @param pageDto 分页查询参数，包含：
   * - page: 当前页码
   * - size: 每页大小
   * - name: 字典名称（可选，模糊查询）
   * - type: 字典类型（可选，精确匹配）
   * - status: 字典状态（可选，精确匹配）
   * @returns 返回字典列表和总数的元组
   */
  async findAll(pageDto: PageDto & Partial<Dict>): Promise<[Dict[], number]> {
    const { page = 1, size = 10, name, type, status } = pageDto;

    const queryBuilder = this.dictRepository.createQueryBuilder('dict');

    // 构建名称模糊查询条件
    if (name) {
      queryBuilder.andWhere('dict.name LIKE :name', { name: `%${name}%` });
    }

    // 构建类型精确匹配条件
    if (type) {
      queryBuilder.andWhere('dict.type = :type', { type });
    }

    // 构建状态精确匹配条件
    if (status !== undefined) {
      queryBuilder.andWhere('dict.status = :status', { status });
    }

    // 设置分页和排序
    queryBuilder
      .skip((page - 1) * size)
      .take(size)
      .orderBy('dict.dictId', 'DESC');

    return await queryBuilder.getManyAndCount();
  }

  /**
   * 根据ID查询字典详情
   * @param id 字典ID
   * @returns 字典实体
   * @throws NotFoundException 当字典不存在时抛出异常
   */
  async findOne(id: number): Promise<Dict> {
    const dict = await this.dictRepository.findOne({
      where: { dictId: id },
    });

    if (!dict) {
      throw new NotFoundException(`Dict with ID ${id} not found`);
    }

    return dict;
  }

  /**
   * 更新字典信息
   * @param updateDictDto 更新字典的数据传输对象
   * @returns 更新后的字典实体
   * @throws NotFoundException 当字典ID不存在时抛出异常
   */
  async update(updateDictDto: UpdateDictDto): Promise<Dict> {
    const { dictId, ...updateData } = updateDictDto;

    if (!dictId) {
      throw new NotFoundException('字典ID不能为空');
    }

    // 先检查字典是否存在
    await this.findOne(dictId);

    // 合并并保存更新的字段
    const dict = this.dictRepository.create({
      dictId,
      ...updateData,
    });

    return await this.dictRepository.save(dict);
  }

  /**
   * 删除字典
   * @param id 字典ID
   * @returns 删除操作的结果
   * @throws NotFoundException 当字典不存在时抛出异常
   */
  async remove(id: number): Promise<any> {
    const dict = await this.findOne(id);

    // 先删除关联的字典数据
    await this.dictDataRepository.createQueryBuilder().delete().from(DictData).where('dictId = :dictId', { dictId: dict.dictId }).execute();

    // 再删除字典本身
    return await this.dictRepository.remove(dict);
  }
}
